package com.data.analysislib.util

import android.app.Application
import androidx.fragment.app.FragmentActivity
import com.google.android.play.core.review.ReviewInfo
import com.google.android.play.core.review.ReviewManager
import com.google.android.play.core.review.ReviewManagerFactory


object AppReviewUtil {

    private var _reviewManager: ReviewManager? = null


    private var _reviewInfo: ReviewInfo? = null


    fun init(context: Application) {
        _reviewManager = ReviewManagerFactory.create(context)
        val request = _reviewManager?.requestReviewFlow()
        request?.addOnCompleteListener { task ->
            if (task.isSuccessful) {
                _reviewInfo = task.result
            } else {
                println("reviewErrorCode: ERROR")
            }
        }
    }

    fun launchReviewFlow(activity: FragmentActivity, completed: (Boolean) -> Unit) {
        if (_reviewInfo == null) {
            completed.invoke(false)
        }

        _reviewInfo?.let {
            val flow = _reviewManager?.launchReviewFlow(activity, it)

            if (flow == null) {
                completed.invoke(false)
            }

            flow?.addOnCompleteListener {
                completed.invoke(true)
            }
        }
    }
}